package com.nuaa.community.controller;

import com.google.code.kaptcha.Producer;
import com.nuaa.community.entity.User;
import com.nuaa.community.service.LoginService;
import com.nuaa.community.service.UserService;
import com.nuaa.community.util.CommunityConstant;


import com.nuaa.community.util.CommunityUtil;
import com.nuaa.community.util.RedisKeyUtil;
import io.micrometer.common.util.StringUtils;
import jakarta.servlet.http.Cookie;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * ClassName: LoginController
 * Package: com.nuaa.community.controller
 * Description: 登录
 */
@Controller
public class LoginController implements CommunityConstant {

    private static final Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Autowired
    private UserService userService;

    @Autowired
    private Producer KaptchaProducer;

    @Autowired
    private LoginService loginService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Value("${server.servlet.context-path}")
    private String contextPath;


    @RequestMapping(path = "/register", method = RequestMethod.GET)
    public String getRegisterPage(){
        return "site/register";
    }

    /**
     * 获取登陆页面
     * @return
     */
    @RequestMapping(path = "/login", method = RequestMethod.GET)
    public String getLoginPage(){
        return "site/login";
    }

    /**
     * 用户注册
     * @param model
     * @param user
     * @return
     */
    @PostMapping(path="/register")
    public String register(Model model, User user){
        logger.info("注册业务");
        Map<String, Object> map = userService.register(user);
        if (map == null || map.isEmpty()){
            model.addAttribute("msg", "注册成功，我们已经向您的邮箱发送了一封激活邮件，请尽快激活!");
            model.addAttribute("target", "/index");
            return "site/operate-result";
        } else {
            model.addAttribute("usernameMsg", map.get("usernameMsg"));
            model.addAttribute("passwordMsg", map.get("passwordMsg"));
            model.addAttribute("emailMsg", map.get("emailMsg"));
            return "site/register";
        }
    }

    /**
     * 获取激活码
     * @param model
     * @param userId
     * @param code
     * @return
     */
    @GetMapping(path = "/activation/{userId}/{code}")
    public String activation(Model model, @PathVariable("userId") int userId, @PathVariable("code") String code){
        logger.info("检验账号是否被激活，并激活");
        int result = userService.activation(userId, code);
        if (result == ACTIVATION_SUCCESS)   {
            model.addAttribute("msg", "激活成功，您的账号已经可以正常使用了!");
            model.addAttribute("target", "/login");
        } else if (result == ACTIVATION_REPEAT){
            model.addAttribute("msg", "无效操作，该账号已经被激活!");
            model.addAttribute("target", "/index");
        } else {
            model.addAttribute("msg", "激活失败，您提供的激活码不正确!");
            model.addAttribute("target", "/index");
        }
        return "site/operate-result";
    }

    /**
     * 生成验证码
     * @param response
     */
    @GetMapping(path = "/kaptcha")
    public void getKaptcha(HttpServletResponse response){
        logger.info("生成验证码");
        // 生成验证码
        String text = KaptchaProducer.createText();
        BufferedImage image = KaptchaProducer.createImage(text);
        // 将验证码存入session
//        session.setAttribute("kaptcha", text);
        // 验证码的归属
        String kaptchaOwner = CommunityUtil.generateUUID();
        Cookie cookie = new Cookie("kaptchaOwner", kaptchaOwner);
        cookie.setMaxAge(60);
        cookie.setPath(contextPath);
        response.addCookie(cookie);
        // 将验证码存入redis
        String redisKey = RedisKeyUtil.getKaptchaKey(kaptchaOwner);
        redisTemplate.opsForValue().set(redisKey, text, 60, TimeUnit.SECONDS);

        // 将图片输出给浏览器
        response.setContentType("image/png");
        try {
            ServletOutputStream os = response.getOutputStream();
            ImageIO.write(image, "png", os);
            logger.info("验证码：{}",text);
        } catch (IOException e) {
            logger.error("响应验证码失败：" + e.getMessage());
        }
    }

    /**
     * 登录业务实现
     * @param username
     * @param password
     * @param code
     * @param rememberme
     * @param model
     * @param response
     * @return
     */
    @PostMapping(path = "login")
    public String login(String username, String password, String code, boolean rememberme,
                        Model model, HttpServletResponse response,  @CookieValue("kaptchaOwner") String kaptchaOwner){
        logger.info("登录业务");
        // 检验验证码
//        String kaptcha = (String) session.getAttribute("kaptcha");
        String kaptcha = null;
        if (StringUtils.isNotBlank(kaptchaOwner)) {
            String redisKey = RedisKeyUtil.getKaptchaKey(kaptchaOwner);
            kaptcha = (String) redisTemplate.opsForValue().get(redisKey);
        }

        if (StringUtils.isBlank(kaptcha) || StringUtils.isBlank(code) || !kaptcha.equalsIgnoreCase(code)){
            model.addAttribute("codeMsg", "验证码不正确");
            // 返回登录页面
            return "/site/login";
        }
        // 设置session记住的时间
        int expiredSeconds = rememberme ? REMEMBER_EXPIRED_SECONDS : DEFAULT_EXPIRED_SECONDS;
        // 检查账号，密码
        Map<String, Object> map = loginService.login(username, password, expiredSeconds);
        if (map.containsKey("ticket")){
            // 登录成功记录cookie，并设置路径和保留时间
            Cookie cookie = new Cookie("ticket", map.get("ticket").toString());
            cookie.setPath(contextPath);
            cookie.setMaxAge(expiredSeconds);
            response.addCookie(cookie);
            // 重定向到首页
            return "redirect:/index";
        } else {
            // 返回错误信息
            model.addAttribute("usernameMsg", map.get("usernameMsg"));
            model.addAttribute("passwordMsg", map.get("passwordMsg"));
            // 返回登录页面
            return "/site/login";
        }
    }

    /**
     * 退出登录并清理用户的认证信息
     * @param ticket
     * @return
     */
    @GetMapping(path = "/logout")
    public String logout(@CookieValue("ticket") String ticket){
        loginService.logout(ticket);
        SecurityContextHolder.clearContext();
        return "redirect:/login";
    }
}
